package com.zhou.framework.config;

import com.zhou.framework.constant.AppEnum;
import com.zhou.framework.constant.CacheKeyEnum;
import com.zhou.framework.redis.util.RedisUtil;
import com.zhou.org.dao.BlackList;
import com.zhou.framework.redis.util.RedisLock;
import com.zhou.util.StringTool;
import com.zhou.org.service.BlackListService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lang.zhou
 * @date 2022/5/6 16:55
 */
@Configuration
@Slf4j
public class BlackListConfig {
    private RedisUtil redisUtil ;
    private RedisLock redisLock ;

    public BlackListConfig(RedisUtil redisUtil, BlackListService service, RedisLock redisLock) {
        this.redisUtil = redisUtil;

        this.redisLock = redisLock;
        List<BlackList> settings = service.list();
        this.refreshCache(settings);
    }

    public BlackList getBlackList(String host){
        return  redisUtil.getHash(CacheKeyEnum.BLACK_LIST,host);
    }
    public boolean inBlackList(BlackList i){
        if(i != null && i.getStatus() == 1){
            long now = new Date().getTime();
            return now >= i.getCreateDt().getTime() && (i.getReleaseDt() == null || now <= i.getReleaseDt().getTime());
        }
        return false;
    }

    public void putBlackItem(BlackList item){
        redisUtil.setHash(CacheKeyEnum.BLACK_LIST,item.getHost(),item);
    }
    public void removeBlackItem(BlackList item){
        redisUtil.delHash(CacheKeyEnum.BLACK_LIST,item.getHost());
    }

    /**
     * 刷新黑名单缓存
     */
    public boolean refreshCache(List<BlackList> settings){
        return redisLock.lockAndRun(AppEnum.BLACK_LOCK_KEY, AppEnum.DEFAULT_LOCK_TIME, () -> {
            Map<String,BlackList> bm = new HashMap<>(settings.size());
            for(BlackList setting : settings){
                String host = StringTool.safeToString(setting.getHost(),"").trim();
                if(host.length() > 0){
                    bm.put(setting.getHost(),setting);
                }
            }
            redisUtil.del(CacheKeyEnum.BLACK_LIST);
            redisUtil.setHash(CacheKeyEnum.BLACK_LIST,bm);
            log.info("系统黑名单缓存刷新完成！");
        });
    }
}
